//
//  StatusListViewModel.m
//  OCMicroBlog
//
//  Created by 002 on 15/11/6.
//  Copyright © 2015年 002. All rights reserved.
//

#import "StatusListViewModel.h"
#include "NetworkTools.h"
#import "SDWebImageManager.h"

@interface StatusListViewModel ()

@end

@implementation StatusListViewModel

/**
 *  加载微博数据库
 *
 *  @param isPullup 是否上拉刷新
 *  @param finished 完成回调
 */
- (void)loadStatus:(BOOL)isPullup finished:(finishedCallBack)finished {

    // 下拉刷新 - 数组中第一条微博的id
    NSUInteger since_id = isPullup ? 0 : self.statusList.firstObject.status.id;
    
    // 上拉刷新 - 数组中最后一条微博的id
    NSUInteger max_id = isPullup ? self.statusList.lastObject.status.id : 0;
    
    self.pulldownCount = (since_id > 0 ? self.statusList.count : 0);
    
    [[NetworkTools sharedTools] loadStatus:since_id max_id:max_id finished:^(id result, NSError *error) {
        // 1. 判断是否有误
        if (error) {
            finished(false);
            return ;
        }
        
        // 2. 判断其他数据类型
        NSArray *array = result[@"statuses"];
        NSLog(@"刷新到%zd条数据",array.count);
        
        // 3. 字典转模型
//        NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:array.count];
        if (array) {
            if (since_id > 0) {
                for (NSInteger i = array.count - 1; i >= 0 ; --i) {
                    NSDictionary *dict = array[i];
                    StatusViewModel *svm = [StatusViewModel initWithStatus:[Status initWithDict:dict]];
                    [self.statusList insertObject:svm atIndex:0];
                }
            }
            else {
                for (NSDictionary *dict in array) {
                    StatusViewModel *svm = [StatusViewModel initWithStatus:[Status initWithDict:dict]];
                    [self.statusList addObject:svm];
                }
            }
        }
        
        // 5. 完成回调
        finished(true);
        
        // 6. 缓存图片
        [self cacheSingleImage:self.statusList finished:finished];
    }];

}

/**
 *  缓存单张图片
 */
- (void)cacheSingleImage:(NSArray<StatusViewModel *> *) array finished:(finishedCallBack)finished {
    
    // 1. 创建调度组
    dispatch_group_t group = dispatch_group_create();
    
    // 缓存数据长度
    __block NSUInteger dataLength = 0;
    
    // 2. 便利视图模型
    for (StatusViewModel *vm in array) {
        
        // 1). 只缓存单张图片
        if (vm.thumbnailUrls.count != 1) {
            continue;
        }
        
        // 2). 获取url
        NSURL *url = vm.thumbnailUrls[0];
//        NSLog(@"开始缓存图像%@",url);
        
        // SDWebImage - 下载图像(缓存是自动完成的)
        // 入组 - 监听后续的 block
        dispatch_group_enter(group);
        
        // 3). 下载图片
        [[SDWebImageManager sharedManager] downloadImageWithURL:url options:SDWebImageRetryFailed progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            
            // 单图下载完后计算长度
            if (image) {
                
                NSData *data = UIImagePNGRepresentation(image);
                
                // 累加二进制数据
                dataLength += data.length;
            }
            // 出组
            dispatch_group_leave(group);
        }];
    }
    
//    NSLog(@"%@",NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true));
    // 3. 监听调度组完成
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//        NSLog(@"缓存完成%zdK",dataLength / 1024);
    });
    // 完成回调，刷新表格
    finished(true);
}

#pragma mark - 懒加载
- (NSMutableArray<StatusViewModel *> *)statusList {
    if (!_statusList) {
        _statusList = [[NSMutableArray<StatusViewModel *> alloc] init];
    }
    return _statusList;
}
@end
